# -*- coding: utf-8 -*-

import sys
import time
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
#import cv2
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QLabel, QLineEdit, QGridLayout, QMessageBox)


import xml.etree.ElementTree as ET

from PIL import Image
import svgutils.transform as sg
from svgutils.compose import Figure


import cairosvg
import rpyc
import threading
import copy
conn = rpyc.connect("152.136.196.35", 9002)
service = conn.root



ET.register_namespace("","http://www.w3.org/2000/svg")
#svg_path1 = 'C:/Users/16006/Desktop/解析软件的开发/svg文件处理前/30-40-test.svg'
#svg_path2 = 'C:/Users/16006/Desktop/解析软件的开发/svg文件处理前/40-40-东宝5211314-2.svg'
#png_path1 = '1.png'
#png_path2 = '2.png'

#ele_root = ET.parse(svg_path1).getroot()

#width = ele_root.get('width')
#height = ele_root.get('height')
#cairosvg.svg2png(url=svg_path1, write_to=png_path1,dpi=600)
#cairosvg.svg2png(url=svg_path2, write_to=png_path2,dpi=600)


#merged_svg = ET.Element('svg')


#svg1 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\60-35-大哪吒和金刚葫芦娃+卡▲-1.svg').getroot()
#svg2 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\60-35-大哪吒和金刚葫芦娃+卡▲-2.svg').getroot()


## Create a new SVG element


## Add the attributes from one of the original SVGs to the merged SVG
#merged_svg.attrib = svg2.attrib

## Add the contents of each SVG to the merged SVG
#for elem in svg1:
#    merged_svg.append(elem)
#for elem in svg2:
#    merged_svg.append(elem)


## Write the merged SVG to a file
#ET.ElementTree(merged_svg).write('merged.svg')



#merged_svg2 = ET.Element('svg')


#svg3 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-1.svg').getroot()
#svg4 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-2.svg').getroot()


## Create a new SVG element


## Add the attributes from one of the original SVGs to the merged SVG
#merged_svg2.attrib = svg3.attrib

## Add the contents of each SVG to the merged SVG
#for elem in svg3:
#    merged_svg.append(elem)
#for elem in svg4:
#    merged_svg.append(elem)


## Write the merged SVG to a files
#ET.ElementTree(merged_svg).write('merged2.svg')










class MergeSvg(object):
    dict_svg = {}
    dir_path = './'
    def split_svg(self, svg_list, path_len, isdir):
        if isdir == 1:
            for ele in svg_list:
                curr_key =  ele[path_len + 1: -6]
                if curr_key in self.dict_svg.keys():
                    self.dict_svg[curr_key].append(ele)
                else:
                    self.dict_svg[curr_key] = []
                    self.dict_svg[curr_key].append(ele)
            #self.merge_svg(self.dict_svg)
            self.merge_svg(self.dict_svg)
        else:
            for ele in svg_list:
                curr_key = ele[path_len + 1: -6];
                if curr_key in self.dict_svg.keys():
                    self.dict_svg[curr_key].append(ele)
                else:
                    self.dict_svg[curr_key] = []
                    self.dict_svg[curr_key].append(ele)
                self.merge_svg(self.dict_svg)
    

    def merge_two(self, svg_node):
        node_key = ""
        flag = False
        for curr_key in svg_node.keys():
            
            node_key = curr_key
            ele_file_list  = svg_node[curr_key]
            merged_svg = ""
            merged_svg = ET.Element('svg')
            root = ET.Element('svg')
            for ele_file in ele_file_list:
                tree = ET.parse(ele_file)
                svg = tree.getroot()
                root.extend(svg)
            merged_svg = ET.tostring(root, encoding='unicode')
            save_svg_path = self.dir_path + "/" + node_key + ".svg"
            with open(save_svg_path , 'w') as file:
                 file.write( merged_svg)
    
            #cairosvg.svg2png(node_key + '.svg', node_key + "_效果图.png")
            write_to_path = self.dir_path +  "/" + node_key + "_效果图.png"
            cairosvg.svg2png(url = save_svg_path, write_to = write_to_path, dpi=600)
            self.rescale_png(write_to_path)

    def rescale_png(self, img_png):
        im = Image.open(img_png)

        # Resize the image to 50% of its original size
        scale_h = float(im.width / 800)

        scale  =  1.0
        if scale_h > 1:
            scale = scale_h

        #if im.width > 6000:
         #   scale = 12
        new_width = int(im.width / scale_h)
        new_height = int(im.height / scale_h)
        im = im.resize((new_width, new_height))

        # Save the resized image in a new file
        im.save(img_png)
           

    def merge_svg(self, svg_node):        
        node_key = ""
        flag = False
        for curr_key in svg_node.keys(): 
            node_key = curr_key
            ele_file_list  = svg_node[curr_key]
            if len(ele_file_list) == 1:
                continue
            merged_svg = ""
            #merged_svg = ET.Element('svg', width='500', height='500')
            merged_svg = ET.Element('svg')
            #ele_file_list = []
            #ele_file_list .append('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-1.svg')
            #ele_file_list .append('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-2.svg')
            flag = False
            for ele_file in ele_file_list:
                
                ele_root = ET.parse(ele_file).getroot()
                if flag == False:
                    #width = ele_root.get('width')
                    #height = ele_root.get('height')
                    #merged_svg.set("width",width)
                   # merged_svg.set("height",height)xmlns="http://www.w3.org/2000/svg"
                    
                    flag = True
                    merged_svg.attrib = ele_root.attrib
                    #merged_svg.set("xmlns", "http://www.w3.org/2000/svg")
                for  ele_node in ele_root:
                    merged_svg.append(ele_node)

            save_svg_path = self.dir_path + "/" + node_key + ".svg"

            ET.ElementTree(merged_svg).write( save_svg_path)
            #cairosvg.svg2png(node_key + '.svg', node_key + "_效果图.png")
            write_to_png = write_to = self.dir_path +  "/" + node_key + "_效果图.png"
            #print("save in  ---->" + save_svg_path )
            #print("read from ---->" + save_svg_path + " write to------->" +  write_to_png)

            cairosvg.svg2png(url = save_svg_path, write_to = write_to_png, dpi=600)
            self.rescale_png(write_to_png)





class Ui_Dialog(object):
    def setupLogin(self,Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.setEnabled(True)


    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.setEnabled(True)
        Dialog.resize(959/3, 539/3)
        Dialog.setMinimumSize(QtCore.QSize(959/3, 539/3))
        Dialog.setMaximumSize(QtCore.QSize(1920/3, 1080/3))
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(0, 0, 959/3, 539/3))
        self.label.setAcceptDrops(False)
        self.label.setScaledContents(False)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Svg"))
        self.label.setText(_translate("Dialog", "拖拽svg文件或者目录至此处"))

#读取中文路径
def cv_imread(file_path):
    cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
    return cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)

class mwindow(QWidget, Ui_Dialog):
    multi_thread = []
    def __init__(self):
        super(mwindow, self).__init__()
        self.setupUi(self)
        # 调用Drops方法
        self.setAcceptDrops(True)
        # 图片
        self.img = None
    def merg_svg(self,dir_List):
        print("merge")

    # 鼠标拖入事件
    def dragEnterEvent(self, evn):
        # print('鼠标拖入窗口了')
        # 鼠标放开函数事件
        evn.accept()
 
    # 鼠标放开执行


        #call_event(evn)

    def exec_dir(self, svg_list, dir_path, path_len):
        
        run_svg = MergeSvg()
        run_svg.dir_path = dir_path
        run_svg.split_svg(svg_list, path_len, 1)

    def dropEvent(self, evn):
        # 判断文件类型
        if evn.mimeData().hasUrls():
            # 获取文件路径
            file_path =  evn.mimeData().urls()[0].toLocalFile()
            url_length = len(evn.mimeData().urls())
            
            if url_length > 1:
                #y拖入的是文件
                svg_list = []

                dir_path = os.path.dirname(evn.mimeData().urls()[0].toLocalFile())
                path_len = len(dir_path)
                for idx in range(0, url_length):
                    curr_file = evn.mimeData().urls()[idx].toLocalFile()
                    file_type = curr_file[-3:]
                    if file_type == "svg":
                        svg_list.append(curr_file)
                if len(svg_list) > 0 :
                    run_svg = MergeSvg()
                    run_svg.dir_path = dir_path
                    run_svg.split_svg(svg_list, path_len, 0)
            else:
                is_dot = file_path[-4: -3]
                if is_dot == ".":
                    file_type = file_path[-3:]
                    if  file_type == "svg":
                        print("svg")
                        run_svg = MergeSvg()
                        run_svg.dir_path = os.path.dirname(evn.mimeData().urls()[0].toLocalFile())
                        single_file = evn.mimeData().urls()[0].toLocalFile()
                        path_len = len(run_svg.dir_path)
                        node_key = single_file[path_len + 1: -6]
                        #svg_list = []
                        #svg_list.append(evn.mimeData().urls()[0].toLocalFile())
                        #run_svg.split_svg(svg_list, path_len, 0)

                        cairosvg.svg2png(url = single_file, write_to = run_svg.dir_path +  "/" + node_key + "_效果图.png", dpi=50)
                        return 
                    else:
                        return 

                path_len = len(file_path)
                file = file_path
                for root, dirs, files in os.walk(file):
                        if root != file:
                            break
                svg_list = []
                for file in files:
                     path = os.path.join(root, file)
                     file_type = path[-3:]
                     if file_type == "svg":
                         svg_list.append(path)
                     print(path)
                #exec_dir
                self.multi_thread.append(threading.Thread(target=self.exec_dir, args =( copy.deepcopy(svg_list), evn.mimeData().urls()[0].toLocalFile(), path_len)));
                self.multi_thread[0].start()
                #run_svg = MergeSvg()
                #dir_path = evn.mimeData().urls()[0].toLocalFile()
                #run_svg.dir_path = dir_path
                #run_svg.split_svg(svg_list, path_len, 1)

            # opencv 转qimage
            #qimg = QImage(self.img.data, self.img.shape[1], self.img.shape[0], self.img.shape[1]*self.img.shape[2],QImage.Format_RGB888)
            # 显示图片 自适应
            #self.label.setPixmap(QPixmap.fromImage(qimg).scaled(self.label.width(), self.label.height(), Qt.KeepAspectRatio))
        # print('鼠标放开了')
 
    #def dropEvent(self, evn):
        #local_file = evn.mimeData().urls()[0].toLocalFile()
        #thread = threading.Thread(target=call_event, args =(self, eve))
        #self.multi_thread.append(threading.Thread(target=self.call_event, args =( copy.deepcopy(evn),)));
        #self.multi_thread[0].start()

    def dragMoveEvent(self, evn):
        pass
        # print('鼠标移入')



class LoginForm(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Login Form')
        self.resize(500, 120)       
        layout = QGridLayout()      
        label_name = QLabel('<font size="4"> Username </font>')
        self.lineEdit_username = QLineEdit()
        self.lineEdit_username.setPlaceholderText('Please enter your username')
        layout.addWidget(label_name, 0, 0)
        layout.addWidget(self.lineEdit_username, 0, 1)      
        label_password = QLabel('<font size="4"> Password </font>')
        self.lineEdit_password = QLineEdit()
        self.lineEdit_password.setPlaceholderText('Please enter your password')
        layout.addWidget(label_password, 1, 0)
        layout.addWidget(self.lineEdit_password, 1, 1)      
        button_login = QPushButton('Login')
        button_login.clicked.connect(self.check_password)
        layout.addWidget(button_login, 2, 0, 1, 2)
        layout.setRowMinimumHeight(2, 75)       
        self.setLayout(layout)

    def check_password(self):
        msg = QMessageBox() 
        print(service.tocken('admin', '1234564'))  # prints 5
        if service.tocken(self.lineEdit_username.text(), self.lineEdit_password.text()):
            msg.setText('Success')
            deal_win.show()
            self.close()
            #msg.exec_()
            #app.quit()
        else:
           msg.setText('Incorrect Password')
           msg.exec_()
if __name__ == '__main__':
    app=QApplication(sys.argv)
    #初始化窗口
    #m=mwindow()
    #m.show()
    #sys.exit(app.exec_())
    deal_win = mwindow()
    m = LoginForm()
    m.show()
    sys.exit(app.exec_())


